package com.qf.common.oss.utils;

import cn.hutool.core.date.DateUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.ObjectMetadata;
import com.qf.common.oss.config.OssConfigProperties;
import com.qf.common.oss.service.FileUploadService;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

/**
 * @author chengqiang
 * @Create 2024-01-20-11:01
 * @Description:
 */
@Component
public class FileUtils {
    public static final String OSS_IMAGE_PREFIX = "images";
    @Resource
    private OSS oss;
    @Resource
    private OssConfigProperties ossConfigProperties;

    public  String uploadImage(MultipartFile multipartFile ,String path) throws IOException {
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType("image/jpg");
        //
        InputStream inputStream = multipartFile.getInputStream();
        // 获取原始文件的名称
        String originalFilename = multipartFile.getOriginalFilename();
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
        /*
         * 上传文件的 bucketName
         * 文件上传的路径和名字
         *
         */
        Date currentDate = DateUtil.date();
        String format = DateUtil.format(currentDate, "yyyyMMddHHmmss");
        String now = DateUtil.format(currentDate, "yyyyMMdd");
        String key = OSS_IMAGE_PREFIX+"/"+path+"/" +now +"/" + format +suffixName;

        oss.putObject(ossConfigProperties.getBucketName(), key, inputStream,objectMetadata);


        return ossConfigProperties.getDoMain()+key;
    }
}
